<template>
    <div class="login-container h-full overflow-hidden relative">
        <!-- 背景渐变动画 -->
        <div class="animated-bg" />

        <!-- 浮动粒子效果 -->
        <div class="particles">
            <div v-for="i in 12" :key="i" class="particle" :style="getParticleStyle(i)" />
        </div>

        <!-- 登录卡片 -->
        <div class="login-card">
            <div class="card-sidebar">
                <div class="sidebar-content">
                    <div class="logo-icon">🚀</div>
                    <div class="sidebar-text">知库</div>
                </div>
            </div>
            <div class="card-content">
                <div class="content-header">
                    <h1 class="main-title">知库</h1>
                    <p class="subtitle">和更多技术人一起学习</p>
                </div>

                <div class="form-container">
                    <div class="input-group">
                        <input v-model="username" class="form-input" type="text" placeholder="用户名" @focus="onInputFocus"
                            @blur="onInputBlur">
                        <span class="input-label">用户名</span>
                    </div>

                    <div class="input-group">
                        <input v-model="password" class="form-input" type="password" placeholder="密码"
                            @focus="onInputFocus" @blur="onInputBlur">
                        <span class="input-label">密码</span>
                    </div>

                    <transition name="slide-down" mode="out-in">
                        <div v-if="!loginMode" class="register-fields">
                            <div class="input-group">
                                <input v-model="email" class="form-input" type="email" placeholder="邮箱"
                                    @focus="onInputFocus" @blur="onInputBlur">
                                <span class="input-label">邮箱</span>
                            </div>
                            <div class="verification-group">
                                <div class="input-group">
                                    <input v-model="code" class="form-input verification-input" type="text"
                                        placeholder="验证码" @focus="onInputFocus" @blur="onInputBlur">
                                    <span class="input-label">验证码</span>
                                </div>
                                <button class="send-code-btn"
                                    :class="{ 'disabled': sendCodeDisabled, 'loading': sendingCode }"
                                    :disabled="sendCodeDisabled" @click="sendCode">
                                    <span v-if="sendingCode" class="loading-spinner" />
                                    <span v-else>{{ sendCodeButtonText }}</span>
                                </button>
                            </div>
                        </div>
                    </transition>

                    <div class="button-group">
                        <button class="action-btn primary-btn" :class="{ 'active': loginMode, 'loading': isLoading }"
                            :disabled="isLoading" @click="login">
                            <span v-if="isLoading && loginMode" class="loading-spinner" />
                            <span v-else>{{ loginMode ? '🚀 登录' : '登录' }}</span>
                        </button>
                        <button class="action-btn secondary-btn" :class="{ 'active': !loginMode, 'loading': isLoading }"
                            :disabled="isLoading" @click="register">
                            <span v-if="isLoading && !loginMode" class="loading-spinner" />
                            <span v-else>{{ loginMode ? '注册' : '✨ 注册' }}</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { userApi } from '~/utils/api'
import { message } from 'ant-design-vue';
const router = useRouter()

const _user = useUserStore()
const username = ref('')
const password = ref('')
const email = ref('')
const code = ref('')
const loginMode = ref(true)
const countdown = ref(0)
const countdownTimer = ref(null)
const isLoading = ref(false)
const sendingCode = ref(false)

// 粒子动画相关
const getParticleStyle = (_index) => {
    const delay = Math.random() * 20
    const duration = 15 + Math.random() * 10
    const size = 2 + Math.random() * 4
    const left = Math.random() * 100

    return {
        left: `${left}%`,
        width: `${size}px`,
        height: `${size}px`,
        animationDelay: `${delay}s`,
        animationDuration: `${duration}s`
    }
}

// 输入框焦点动画
const onInputFocus = (event) => {
    const inputGroup = event.target.closest('.input-group')
    inputGroup.classList.add('focused')
}

const onInputBlur = (event) => {
    const inputGroup = event.target.closest('.input-group')
    if (!event.target.value) {
        inputGroup.classList.remove('focused')
    }
}

// 计算属性
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const sendCodeDisabled = computed(() => {
    return countdown.value > 0 || !email.value || !emailRegex.test(email.value)
})

const sendCodeButtonText = computed(() => {
    return countdown.value > 0 ? `${countdown.value}s后重试` : '发送验证码'
})

// 显示消息
const showMessage = (text, type = 'success') => {
    message[type](text);
}

// 发送验证码
const sendCode = async () => {
    if (!email.value) {
        showMessage('请输入邮箱地址', 'error')
        return
    }

    sendingCode.value = true
    try {
        const response = await userApi.sendVerificationCodeApi(email.value)
        const data = response

        if (data.success) {
            showMessage(data.message, 'success')
            startCountdown(data.remainingTime || 60)
        } else {
            showMessage(data.error, 'error')
            if (data.remainingTime) {
                startCountdown(data.remainingTime)
            }
        }
    } catch (error) {
        showMessage('发送验证码失败，请稍后重试', 'error')
        console.error('发送验证码错误:', error)
    } finally {
        sendingCode.value = false
    }
}

// 开始倒计时
const startCountdown = (seconds) => {
    countdown.value = seconds
    countdownTimer.value = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
            clearInterval(countdownTimer.value)
            countdownTimer.value = null
        }
    }, 1000)
}

// 注册请求
const registerPost = async () => {
    if (!username.value || !password.value || !email.value || !code.value) {
        showMessage('请填写完整信息', 'error')
        return
    }

    isLoading.value = true
    try {
        const response = await userApi.registerApi({
            username: username.value,
            password: password.value,
            email: email.value,
            verificationCode: code.value
        })
        const data = response

        if (data.success) {
            showMessage('注册成功！', 'success')
            // 注册成功后切换到登录模式
            setTimeout(() => {
                loginMode.value = true
                clearForm()
            }, 2000)
        } else {
            showMessage(data.error, 'error')
        }
    } catch (error) {
        showMessage('注册失败，请稍后重试', 'error')
        console.error('注册错误:', error)
    } finally {
        isLoading.value = false
    }
}

// 登录请求
const loginPost = async () => {
    if (!username.value || !password.value) {
        showMessage('请输入用户名和密码', 'error')
        return
    }

    isLoading.value = true
    try {
        const response = await userApi.loginApi(username.value, password.value)
        const data = response
        if (data.success) {
            showMessage('登录成功！', 'success')
            console.log(data.data, data.token, '登录成功');

            // 设置用户信息和token到store
            _user.setUser(data.data)
            _user.setToken(data.token)

            // 跳转到首页
            router.push('/Studyarea/Forum')
        } else {
            showMessage(data.error, 'error')
        }
    } catch (error) {
        showMessage('登录失败，请稍后重试', 'error')
        console.error('登录错误:', error)
    } finally {
        isLoading.value = false
    }
}

// 清除表单
const clearForm = () => {
    username.value = ''
    password.value = ''
    email.value = ''
    code.value = ''
}

const register = () => {
    if (loginMode.value) {
        loginMode.value = false
        clearForm()
        return
    }
    registerPost()
}

const login = () => {
    if (!loginMode.value) {
        loginMode.value = true
        clearForm()
        return
    }
    loginPost()
}

// 组件卸载时清理定时器
onUnmounted(() => {
    if (countdownTimer.value) {
        clearInterval(countdownTimer.value)
    }
})
</script>

<style scoped>
/* 主容器 */
.login-container {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    position: relative;
    overflow: hidden;
}

/* 动态背景 */
.animated-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
    background-size: 400% 400%;
    animation: gradientShift 8s ease infinite;
}

@keyframes gradientShift {
    0% {
        background-position: 0% 50%;
    }

    50% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0% 50%;
    }
}

/* 粒子效果 */
.particles {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1;
}

.particle {
    position: absolute;
    background: rgba(255, 255, 255, 0.6);
    border-radius: 50%;
    animation: floatUp linear infinite;
}



/* 登录卡片 */
.login-card {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    width: 600px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 10px 20px 40px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    z-index: 10;
}

@keyframes cardEnter {
    0% {
        opacity: 0;
        transform: translate(-50%, -50%) scale(0.8) rotateY(180deg);
    }

    100% {
        opacity: 1;
        transform: translate(-50%, -50%) scale(1) rotateY(0deg);
    }
}

.login-card.register-mode {
    height: 560px;
    animation: cardExpand 0.5s ease-out;
}

@keyframes cardExpand {
    0% {
        height: 480px;
    }

    100% {
        height: 560px;
    }
}

/* 侧边栏 */
.card-sidebar {
    width: 120px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
}

.card-sidebar::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.1) 50%, transparent 70%);
    animation: shimmer 3s ease-in-out infinite;
}

@keyframes shimmer {

    0%,
    100% {
        transform: translateX(-100%);
    }

    50% {
        transform: translateX(100%);
    }
}

.sidebar-content {
    text-align: center;
    color: white;
    z-index: 2;
}

.logo-icon {
    font-size: 2.5rem;
    margin-bottom: 10px;
    animation: bounce 2s ease-in-out infinite;
}

@keyframes bounce {

    0%,
    20%,
    50%,
    80%,
    100% {
        transform: translateY(0);
    }

    40% {
        transform: translateY(-10px);
    }

    60% {
        transform: translateY(-5px);
    }
}

.sidebar-text {
    font-size: 0.9rem;
    font-weight: 600;
    letter-spacing: 1px;
}

/* 卡片内容 */
.card-content {
    flex: 1;
    padding: 40px;
    display: flex;
    flex-direction: column;
}

.content-header {
    text-align: center;
    margin-bottom: 30px;
}

.main-title {
    font-size: 2rem;
    font-weight: 700;
    color: #333;
    margin: 0 0 10px 0;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    animation: titleGlow 2s ease-in-out infinite alternate;
}

@keyframes titleGlow {
    0% {
        filter: brightness(1);
    }

    100% {
        filter: brightness(1.2);
    }
}

.subtitle {
    color: #666;
    font-size: 0.9rem;
    margin: 0;
    border-bottom: 2px solid #eee;
    padding-bottom: 15px;
}

/* 表单容器 */
.form-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

/* 输入框组 */
.input-group {
    position: relative;
    transition: all 0.3s ease;
}

.form-input {
    width: 100%;
    padding: 15px 20px;
    border: 2px solid #e1e5e9;
    border-radius: 12px;
    font-size: 1rem;
    background: rgba(255, 255, 255, 0.8);
    transition: all 0.3s ease;
    outline: none;
}

.form-input:focus {
    border-color: #667eea;
    background: white;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    transform: translateY(-2px);
}

.input-label {
    position: absolute;
    top: 15px;
    left: 20px;
    color: #999;
    font-size: 1rem;
    pointer-events: none;
    transition: all 0.3s ease;
    background: white;
    padding: 0 5px;
}

.input-group.focused .input-label,
.form-input:not(:placeholder-shown)+.input-label {
    top: -8px;
    left: 15px;
    font-size: 0.8rem;
    color: #667eea;
    font-weight: 600;
}

/* 注册字段动画 */
.register-fields {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.slide-down-enter-active,
.slide-down-leave-active {
    transition: all 0.4s ease;
    overflow: hidden;
}

.slide-down-enter-from {
    opacity: 0;
    max-height: 0;
    transform: translateY(-20px);
}

.slide-down-leave-to {
    opacity: 0;
    max-height: 0;
    transform: translateY(-20px);
}

.slide-down-enter-to,
.slide-down-leave-from {
    opacity: 1;
    max-height: 200px;
    transform: translateY(0);
}

/* 验证码组 */
.verification-group {
    display: flex;
    gap: 10px;
    align-items: flex-end;
}

.verification-input {
    flex: 1;
}

.send-code-btn {
    padding: 15px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 12px;
    font-size: 0.9rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    min-width: 120px;
    position: relative;
    overflow: hidden;
}

.send-code-btn:hover:not(.disabled):not(.loading) {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.send-code-btn.disabled {
    background: #ccc;
    cursor: not-allowed;
}

.send-code-btn.loading {
    cursor: not-allowed;
}

/* 按钮组 */
.button-group {
    display: flex;
    gap: 15px;
    margin-top: 20px;
}

.action-btn {
    flex: 1;
    padding: 15px 25px;
    border: 2px solid transparent;
    border-radius: 12px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.primary-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.primary-btn:hover:not(.loading):not(:disabled) {
    transform: translateY(-3px);
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
}

.primary-btn.active {
    animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {

    0%,
    100% {
        box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.4);
    }

    50% {
        box-shadow: 0 0 0 10px rgba(102, 126, 234, 0);
    }
}

.secondary-btn {
    background: white;
    color: #667eea;
    border-color: #667eea;
}

.secondary-btn:hover:not(.loading):not(:disabled) {
    background: #667eea;
    color: white;
    transform: translateY(-3px);
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
}

.secondary-btn.active {
    background: #667eea;
    color: white;
    animation: pulse 2s ease-in-out infinite;
}

.action-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none !important;
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid transparent;
    border-top: 2px solid currentColor;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .login-card {
        width: 90%;
        height: auto;
        min-height: 480px;
        flex-direction: column;
    }

    .card-sidebar {
        width: 100%;
        height: 80px;
        flex-direction: row;
    }

    .sidebar-content {
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .logo-icon {
        font-size: 2rem;
        margin-bottom: 0;
    }

    .sidebar-text {
        font-size: 1.1rem;
    }

    .card-content {
        padding: 30px 20px;
    }

    .main-title {
        font-size: 1.5rem;
    }
}
</style>